package org.jmh.gift.listener;

import org.jmh.gift.constants.OrderConstants;
import org.jmh.gift.dto.DeleteDTO;
import org.jmh.gift.dto.PlaceOrderDTO;
import org.jmh.gift.service.IShopCarService;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 下单时删除购物车数据的消息监听
 */
@Component
@RocketMQMessageListener(topic = OrderConstants.PLACE_ORDER_TX_TOPIC,
        consumerGroup = OrderConstants.PLACE_ORDER_TX_SHOP_CAR_CONSUMER_GROUP)
public class PlaceOrderClearShopCarMessageListener implements RocketMQListener<MessageExt> {

    @Autowired
    private IShopCarService shopCarService;

    @Override
    public void onMessage(MessageExt message) {
        //获取消息队列中的消息
        String s = new String(message.getBody());
        PlaceOrderDTO dto = JSONObject.parseObject(s, PlaceOrderDTO.class);

        //判断是不是购物车页面过来的，如果是，则删除购物车中的相关sku信息
        if(dto.getBuyNow() == 0){
            //说明是购物车过来的，就要删除购物车相关商品信息
            Long userId = dto.getUserId();
            Set<Long> skuIds = dto.getSkuInfos().keySet();
            for (Long skuId : skuIds) {
                DeleteDTO deleteDTO = new DeleteDTO(skuId, userId);
                shopCarService.deleteShopCarBySkuId(deleteDTO);
            }
        }
    }
}
